#include <my_header.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>

void find(char* path,char* target){
    char buf[512],*p;
    int fd=open(path,O_RDONLY);
    if(fd<0){
        perror("open");
        return;
    }
    struct stat st;
    
    if(fstat(fd,&st)<0){
        perror("fstat");
        close(fd);
        return;
    }

    switch(st.st_mode & S_IFMT){
    
    case S_IFREG:
        if(strcmp(path+strlen(path)-strlen(target),target)==0){
            printf("%s\n",path);
            close(fd);
            return;
        }
        break;
    case S_IFDIR:
        if(strlen(path)+1+strlen(target)>sizeof(buf)){
            printf("路径太长\n");
            close(fd);
            return;
        }
        strcpy(buf,path);
        p=buf+strlen(buf);
        *p++='/';
        *p='\0';

        DIR *dir = fdopendir(fd);
        if(dir == NULL){
            perror("fdopendir");
            close(fd);
            return;
        }

        struct dirent *entry;
        while((entry=readdir(dir))){
            if(strcmp(entry->d_name,".")==0 || strcmp(entry->d_name,"..")==0){
                continue;
            }
            strcpy(p, entry->d_name);
            find(buf,target);
        }
        closedir(dir);
        return;
    default:
       return;
    }
    close(fd); 
}

int main(int argc,char* argv[]){
    if(argc<3){
        printf("请输出查询路径和目的文件\n");
        exit(0);
    }
    find(argv[1],argv[2]);
    return 0;
}